package com.gxar.quick.ar.server.base.sdk;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/4/12 09:33
 */
@Slf4j
public class QiMenSDK {

    /**
     * 抽奖
     *
     * @param url        url
     * @param token      token
     * @param activityId 活动id
     * @return 响应
     */
    public static JSONObject lottery(String url, String token, String activityId) {
        HttpRequest httpRequest = HttpUtil.createPost(url + "/award/lottery");
        Map<String, String> params = new HashMap<>();
        params.put("activityId", activityId);
        httpRequest.formStr(params);
        httpRequest.header("access-token", token);
        HttpResponse response = httpRequest.execute();
        String body = response.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (response.getStatus() != 200) {
            if (StringUtils.isNotBlank(jsonObject.getString("message"))) {
                log.info("奇门抽奖失败, {}", jsonObject.getString("message"));
                throw new APIRuntimeException(ResultCodeEnum.QI_MEN_LOTTERY_FAIL.getRet(), jsonObject.getString("message"));
            } else {
                throw new APIRuntimeException(ResultCodeEnum.QI_MEN_LOTTERY_FAIL);
            }
        }
        return jsonObject;
    }

    public static JSONObject writeOff(String url, String token, String prizeHisId) {
        HttpRequest httpRequest = HttpUtil.createPost(url + "/micro/user/writeOff");
        Map<String, String> params = new HashMap<>();
        params.put("prizeHisId", prizeHisId);
        httpRequest.formStr(params);
        httpRequest.header("access-token", token);
        HttpResponse response = httpRequest.execute();
        String body = response.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (response.getStatus() != 200) {
            if (StringUtils.isNotBlank(jsonObject.getString("message"))) {
                log.info("奇门核销失败, {}", jsonObject.getString("message"));
                throw new APIRuntimeException(ResultCodeEnum.QI_MEN_LOTTERY_FAIL.getRet(), jsonObject.getString("message"));
            } else {
                throw new APIRuntimeException(ResultCodeEnum.QI_MEN_LOTTERY_FAIL);
            }
        }
        return jsonObject;
    }
}
